<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "tag".
 *
 * @property integer $id
 * @property string $name
 * @property integer $frequency
 */
class Tag extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tag';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['frequency'], 'integer'],
            [['name'], 'string', 'max' => 128],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'frequency' => 'Frequency',
        ];
    }

    public static function string2array($tags)
    {
        //return preg_split('/\s*,\s*/',trim($tags),-1,PREG_SPLIT_NO_EMPTY);
        if (empty($tags)) return [];
        return explode(',', $tags);
    }

    public static function array2string($tags)
    {
        return implode(',', $tags);
    }

    /**
     * 增加tag方法
     * @param $tags
     */
    public static function addTags($tags)
    {
        if (empty($tags) || !is_array($tags)) return;

        foreach ($tags as $tag) {
            $aTag = Tag::find()->where(['name' => $tag])->one();
            $aTagCount = count($aTag);
            //$aTagCount = Tag::find()->where(['name' => $tag])->count();

            if ($aTagCount) { //存在记录则加1
                $aTag->frequency +=1;
                $aTag->save();
            }else { //创建一条记录
                $newTag = new Tag();
                $newTag->name = $tag;
                $newTag->frequency = 1;
                $newTag->save();
            }
        }
    }

    public static function deleteTags($tags)
    {
        if (empty($tags) || !is_array($tags)) return;

        foreach ($tags as $tag) {
            $aTag = Tag::find()->where(['name' => $tag])->one();
            $aTagCount = Tag::find()->where(['name' => $tag])->count();

            if ($aTagCount) {
                if ($aTag->frequency <= 1) { //等于1时，删除Tag
                    $aTag->delete();
                }else {
                    $aTag->frequency -= 1;
                    $aTag->save();
                }
            }
        }
    }

    /**
     * 更新标签的操作方法
     * @param \String $oldTags
     * @param \String $newTags
     */
    public static function updateFrequency($oldTags, $newTags)
    {
        if (!empty($oldTags) || !empty($newTags)) {
            $oldTagsArray = self::string2array($oldTags);
            $newTagsArray = self::string2array($newTags);

            //先调用addTags方法
            self::addTags( array_values(array_diff($newTagsArray, $oldTagsArray)) );
            self::deleteTags( array_values(array_diff($oldTagsArray, $newTagsArray)));
        }
    }
}
